package communication.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.SocketException;

import communication.ClientConnectionHandle;
import communication.Message;
import communication.MessageFactory;
import communication.MessageType;
import communication.message.*;
import communication.message.Error;

import exception.BadArgumentValueException;
import exception.ParseException;

public class Handle extends ClientConnectionHandle {
	private String nick;

	public Handle(DataInputStream input, DataOutputStream output) {
		super(input, output);
	}

	public Message receiveMessage() throws ParseException, SocketException {
		String s = super.receive();
		Message msg = null;
		//System.out.println("Received:" + s + "\n");
		msg = MessageFactory.fromString(s.trim());
		return msg;
	}

	public void sendLoginResponse(boolean accept)
			throws BadArgumentValueException, IOException {
		if (!accept) {
			throw new BadArgumentValueException(
					"LoginResponse has been send with accept set to \"no\", but no error has been specyfied");
		}
		Message msg = new Message(MessageType.LOGIN_RESPONSE);
		msg.setResponse(new Response(accept));
		super.send(msg);
	}

	public void sendLoginResponse(boolean accept, int errorId)
			throws IOException {
		Message msg = new Message(MessageType.LOGIN_RESPONSE);
		msg.setResponse(new Response(accept));
		if (!accept)
			msg.setError(new Error(errorId));
		super.send(msg);
	}

	public void sendError(String error) throws IOException {
		Message msg = new Message(MessageType.ERROR);
		msg.setError(error);
		super.send(msg);
	}

	public void serverShutdown() throws IOException {
		Message msg = new Message(MessageType.SERVER_SHUTDOWN);
		super.send(msg);
	}

	public String getNick() {
		return nick;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}
}